package fr.utbm.gl52.smartgrid.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.UUID;

import javax.swing.JPanel;

import fr.utbm.gl52.smartgrid.model.device.IDevice;
import fr.utbm.gl52.smartgrid.util.Constants;
import fr.utbm.gl52.smartgrid.util.Controllable;
import fr.utbm.gl52.smartgrid.util.properties.Properties;

@SuppressWarnings("unused")
public class ViewManager implements ActionListener, Controllable, Runnable {

	private MainFrame mainFrame;
	private ActionEvent switchPanelEvent; // TODO à faire pour switcher de
											// MainPanel (propertyEditor/panel
											// settable)

	public ViewManager() {
		this.mainFrame = new MainFrame();
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		String command = e.getActionCommand();

		if (command.startsWith(Constants.PREFIX_CREATE)) // Creating a device
		{
			command = command.substring(Constants.PREFIX_CREATE.length());
			if (Constants.isDebug)
				System.out.println("ViewManager_create " + command); //$NON-NLS-1$
			this.mainFrame.create(command);
		} 
		else if (command.startsWith(Constants.PREFIX_REQUEST)) // Editing an existing device
		{
			int index = command.indexOf("%"); //$NON-NLS-1$
			int id = Integer.parseInt(command.substring(index + 1)); // device
																		// index
			if (Constants.isDebug)
				System.out.println("ViewManager_edit " + e.getActionCommand() //$NON-NLS-1$
						+ id);
		}
		// Removes the property editor panel when it is validated
		else if (command.startsWith(Constants.PREFIX_VALIDATEPPEP)) {
			if (Constants.isDebug)
				System.out.println("ViewManager_validate " + command); //$NON-NLS-1$
			this.mainFrame.setDisplayingOffPanel(true);
			this.mainFrame.switchPanels();
		}
	}

	public void editRequest(UUID id, Map<String, Properties<?>> properties) {
		this.mainFrame.edit(id, properties);
	}

	@Override
	public void addController(ActionListener controller) {
		this.mainFrame.addControllers(this, controller);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		this.mainFrame.setVisible(true);
	}

	public void update(Map<UUID, IDevice> map) {
		this.mainFrame.update(map.values());
	}

	public void setNewPropertyEditorPanel(UUID uuid,
			Map<String, Properties<?>> properties) {
		this.mainFrame.setPropertyEditorPanel(uuid, properties);
	}

	public void setSecondaryPanel(JPanel secondaryPanel) {
		this.mainFrame.setOffPanel(secondaryPanel);
	}
}